#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ ! -z "${feature_musl}" ]; then
    if [ -n "${feature_cross_aarch64}" ]; then
        target_triple=aarch64-unknown-linux-musl
    else
        target_triple=${arch}-unknown-linux-musl
    fi
else
    if [ -n "${feature_cross_aarch64}" ]; then
        target_triple=aarch64-unknown-linux-gnu
    else
        target_triple=${arch}-unknown-linux-gnu
    fi
fi

cd build || exit 1

if [ -n "${feature_only_gcc}" ]; then
    make DESTDIR=${install_root} install-gcc install-target-libgcc || exit 1

    if [ -n "${feature_cross_aarch64}" ]; then
        mkdir -p $install_root/usr/${target_triple} || exit 1
        ln -sfv /usr/include $install_root/usr/${target_triple}/include || exit 1
    fi

    exit 0
fi

make DESTDIR=${install_root} install || exit 1

if [ ${impure} -eq 1 ]; then
    mkdir -p $install_root/usr/bin/gcc-build
    for i in \
        genattr         gencfn-macros  genconditions  genemit     gengenrtl  genmddeps  genpeep        genversion \
        genattr-common  gencheck       gencondmd      genenums    gengtype   genmodes   genpreds \
        genattrtab      genchecksum    genconfig      genextract  genhooks   genopinit  genrecog \
        genautomata     gencodes       genconstants   genflags    genmatch   genoutput  gentarget-def; do
        install -m 755 -v gcc/build/$i $install_root/usr/bin/gcc-build/
    done
fi
